//
//  KAApplyInfoCell.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import RxCocoa
import RxSwift

class KAApplyInfoCell: UITableViewCell {
    
    var editingHandle: ((_ cell:KAApplyInfoCell, _ content:String)->())? = nil
    
    var editingChanged: ((_ cell:KAApplyInfoCell, _ content:String)->())? = nil
    
    var editDidEndHandle: ((_ cell:KAApplyInfoCell, _ tfInfo:KATFInfo)->())? = nil


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.contentView.backgroundColor = .white
    }
    
    private let disposeBag = DisposeBag()
    
    lazy var var_type: ListType = .identification {
        willSet {
            switch newValue {
            case .education: fallthrough
            case .jobStatus: fallthrough
            case .profession: fallthrough
            case .salary: fallthrough
            case .marital: fallthrough
            case .residence: fallthrough
            case .home: fallthrough
            case .city: fallthrough
            case .payDay: fallthrough
            case .entryDate:
                var_clearBtn.isHidden = true
                var_rightArrow.isHidden = false
                contentTF.isUserInteractionEnabled = false
            default:
                var_clearBtn.isHidden = false
                var_rightArrow.isHidden = true
                contentTF.isUserInteractionEnabled = true
            }
        }
    }
    
    lazy var var_bgView: UIView = {
        let var_bgView = UIView();
        var_bgView.layer.masksToBounds = true
        var_bgView.layer.cornerRadius = kscale(10);
        var_bgView.backgroundColor = .colorf2f2f5
        var_bgView.frame = CGRectMake(kscale(20), 0, var_screenWidth-kscale(40), kscale(46))
        return var_bgView
    }()
    
    lazy var contentTF: UITextField = {
        let contentTF = UITextField()
        contentTF.font = UIFont.systemFont(ofSize: kscale(14.0))
        let var_placeholderString = NSMutableAttributedString.init(string: "", attributes: [.font : kFontSize(16), .foregroundColor : UIColor.black])
        contentTF.attributedPlaceholder = var_placeholderString;
        contentTF.textColor = .black
        contentTF.delegate = self;
        contentTF.returnKeyType = .default
        contentTF.keyboardType = .asciiCapable
        contentTF.isUserInteractionEnabled = true
        return contentTF
    }()
    
    lazy var var_clearBtn: UIButton = {
        let var_clearBtn = UIButton()
        var_clearBtn.setImage(UIImage(named: "text_clear"), for: .normal)
        var_clearBtn.setImage(UIImage(named: "text_clear"), for: .selected)
        var_clearBtn.isHidden = true
        var_clearBtn.isUserInteractionEnabled = true
        return var_clearBtn
    }()
    
    lazy var var_rightArrow: UIImageView = {
        let var_rightArrow = UIImageView(image: UIImage(named: "arrow_right"))
        return var_rightArrow
    }()
    
    //var lastDate: Date = Date()
    var lastTimeInterval: TimeInterval = 0
    var tfInfo = KATFInfo()
    
    static func ka_cell(for tableView: UITableView) -> KAApplyInfoCell {
        let var_identifityId = NSStringFromClass(self)
        var var_cell = tableView.dequeueReusableCell(withIdentifier: var_identifityId)
        if var_cell == nil {
            var_cell = KAApplyInfoCell.init(style: .default, reuseIdentifier: var_identifityId)
        }
        return var_cell as! KAApplyInfoCell
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        ka_setUI()
        ka_bindUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KAApplyInfoCell: UITextFieldDelegate {
    func ka_setUI() {
        backgroundColor = .white
        contentView.addSubview(var_bgView)
        var_bgView.addSubview(contentTF)
        var_bgView.addSubview(var_clearBtn)
        var_bgView.addSubview(var_rightArrow)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        var_clearBtn.snp.makeConstraints { make in
            make.width.height.equalTo(kscale(20))
            make.right.equalTo(var_bgView).offset(kscale(-16));
            make.centerY.equalTo(contentView);
        }
        var_rightArrow.snp.makeConstraints { make in
            make.width.height.equalTo(kscale(20))
            make.right.equalTo(var_bgView).offset(kscale(-16));
            make.centerY.equalTo(contentView);
        }
        contentTF.snp.makeConstraints { make in
            make.left.equalTo(kscale(12));
            make.right.equalTo(var_clearBtn.snp.left).offset(kscale(-10));
            make.top.bottom.equalTo(0);
        }
    }
    
    func ka_bindUI() {
        contentTF.rx.text
            .orEmpty
            .map {  $0.isEmpty }
            .bind(to: var_clearBtn.rx.isHidden)
            .disposed(by: disposeBag)
        
        var_clearBtn.rx.tap
            .subscribe(onNext: {
                self.contentTF.text = ""
                if self.editingHandle != nil {
                    self.editingHandle!(self, "")
                }
            })
            .disposed(by: disposeBag)
        
        //一上来就会监听，如果不需要可以换用editingChanged（只在输入时监听）
//        contentTF.rx.text
//            .orEmpty
//            .subscribe(onNext: { text in
//                //print("Text changed: \(text)")
//                if self.editingHandle != nil {
//                    self.editingHandle!(self, text)
//                }
//                let currentDate = Date()
//                let interval = Date.timeInterval(start: self.lastDate, end: currentDate)
//                let newLog = "\(interval):\(self.contentTF.text ?? ""):0"
//                self.tfInfo.val.append(newLog)
//                self.lastDate = currentDate
//                print("val:------ \(self.tfInfo.val)")
//                
//                if self.editingChanged != nil {
//                    self.editingChanged!(self, self.contentTF.text!)
//                }
//            })
//            .disposed(by: disposeBag)
        
        //获得焦点1 输入0 失去焦点2
        contentTF.rx.controlEvent(.editingDidBegin)
            .subscribe(onNext: {
                //设置最后编辑时间
                self.lastTimeInterval = Date().ka_timeInterval()
                //判断若是第一次进行编辑，设置开始时间和最后编辑时间一致
                if self.tfInfo.stayTime == 0 {
                    self.tfInfo.startTime = self.lastTimeInterval
                }
                let str = self.tfInfo.val.isEmpty ? "0:\(self.contentTF.text ?? ""):1," : ",0:\(self.contentTF.text ?? ""):1,"
                self.tfInfo.val.append(str)
            })
            .disposed(by: disposeBag)
        
        contentTF.rx.controlEvent(.editingDidEnd)
            .subscribe(onNext: {
                //let currentDate = Date()
                //let interval = Date.timeInterval(start: self.lastDate, end: currentDate)
                let currentTimeInterval = Date().ka_timeInterval()
                let interval = Date.timeIntervalWith(startInterval: self.lastTimeInterval, endInterval: currentTimeInterval)
                let newLog = "\(Int(interval)):\(self.contentTF.text ?? ""):2"
                self.tfInfo.val.append(newLog)
                self.lastTimeInterval = currentTimeInterval
                self.tfInfo.endTime = currentTimeInterval
                self.tfInfo.stayTime = Date.timeIntervalWith(startInterval: self.tfInfo.startTime, endInterval: self.tfInfo.endTime)
                self.lastTimeInterval = currentTimeInterval
                print("val:------ \(self.tfInfo.val)")
                
                if self.editDidEndHandle != nil {
                    self.editDidEndHandle!(self, self.tfInfo)
                }
            })
            .disposed(by: disposeBag)
        
        contentTF.rx.controlEvent(.editingChanged)
            .subscribe(onNext: {
                print("Text editing Changed: \(self.contentTF.text!)")
//                if self.editingChanged != nil {
//                    self.editingChanged!(self, self.contentTF.text!)
//                }
                
                if self.editingHandle != nil {
                    self.editingHandle!(self, self.contentTF.text!)
                }
                let currentTimeInterval = Date().ka_timeInterval()
                //let interval = Date.timeInterval(start: self.lastDate, end: currentDate)
                let interval = Date.timeIntervalWith(startInterval: self.tfInfo.startTime, endInterval: currentTimeInterval)

                let newLog = "\(Int(interval)):\(self.contentTF.text ?? ""):0,"
                self.tfInfo.val.append(newLog)
                self.lastTimeInterval = currentTimeInterval
                print("val:------ \(self.tfInfo.val)")
                
                if self.editingChanged != nil {
                    self.editingChanged!(self, self.contentTF.text!)
                }
            })
            .disposed(by: disposeBag)
        
       
        
    }
}
